<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 警示语句 -->
      <el-alert title="添加商品信息" type="warning" show-icon center :closable="false"></el-alert>
      <!-- 步骤条 -->
      <!-- 步骤条与tab栏联动，公用activeIndex属性，当点击tab栏时，name的值会保存到activeIndex中，使步骤条的值也发生变化 -->
      <el-steps :active="activeIndex - 0" align-center finish-status="success">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 表格 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
        label-position="top"
      >
        <!-- 左侧tab栏 -->
        <el-tabs
          :tab-position="'left'"
          v-model="activeIndex"
          :before-leave="beforeTabLeave"
          @tab-click="tabChange"
        >
          <!-- 第一栏 -->
          <el-tab-pane label="基本信息" name="0">
            <!-- 信息表单 -->
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类">
              <!-- 级联选择器 -->
              <template>
                <el-cascader
                  v-model="addForm.goods_cat"
                  :options="goodList"
                  :props="props"
                  @change="handleChange"
                ></el-cascader>
              </template>
            </el-form-item>
          </el-tab-pane>
          <!-- 第二栏 -->
          <el-tab-pane label="商品参数" name="1">
            <!-- 多选框 -->
            <!-- 循环获取动态参数标题 -->
            <el-form-item v-for="(item, i) in manyTableData" :label="item.attr_name" :key="i">
              <!-- 第二次循环获取参数名 -->
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox v-for="(item2, i2) in item.attr_vals" :label="item2" :key="i2" border></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <!-- 第三栏 -->
          <el-tab-pane label="商品属性" name="2">
            <!-- 静态属性表单 -->
            <el-form-item :label="item.attr_name" v-for="item in onlyTableData" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <!-- 第四栏 -->
          <el-tab-pane label="商品图片" name="3">
            <!-- upload有默认的请求头，没有使用预先设置的axios拦截器，所以上传失败，需要设置header属性 -->
            <el-upload
              :action="uploadURL"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headerObj"
              :on-success="addPic"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <!-- 第五栏 -->
          <el-tab-pane label="商品内容" name="4">
            <quill-editor ref="myQuillEditor" v-model="addForm.goods_introduce" class="editArea" />
            <el-button type="primary" class="addBtn" @click="addGoods">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <el-dialog title="预览图片" :visible.sync="preDialogVisible" width="50%">
      <img :src="pathURL" style="width:100%" />
    </el-dialog>
  </div>
</template>

<script>
import _ from 'lodash'
export default {
  data() {
    return {
      // tab栏切换
      activeIndex: '0',
      //   表单内容
      addForm: {
        goods_name: '',
        goods_price: '0',
        goods_weight: '0',
        goods_number: '0',
        goods_cat: [],
        pics: [],
        goods_introduce: '',
        attr: []
      },
      //   表单校验规则
      addFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', triggle: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', triggle: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', triggle: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', triggle: 'blur' }
        ]
      },
      //   保存分类id值
      //   selectKeys: [],
      // 获取分类信息
      goodList: [],
      // 级联选择器的配置项
      props: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 动态参数数据
      manyTableData: [],
      //   静态参数数据
      onlyTableData: [],
      //   上传图片的url地址
      uploadURL: 'http://127.0.0.1:8888/api/private/v1/upload',
      // 设置图片上传headers请求头
      headerObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      // 控制对话框显示
      preDialogVisible: false,
      // 图片预览路径
      pathURL: ''
    }
  },
  created() {
    this.getGoodsList()
  },
  methods: {
    async getGoodsList() {
      const { data: res } = await this.$http.get('categories')
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类失败！')
      }
      this.goodList = res.data
    },
    // 级联选择器变化时
    handleChange() {
      if (this.addForm.goods_cat.length !== 3) {
        this.$message.error('只允许选择三级分类')
        return (this.addForm.goods_cat = [])
      }
    },
    // 在tab栏切换时执行函数
    beforeTabLeave(activeName, oldActiveName) {
      //   console.log('进入' + activeName)
      //   console.log('离开' + oldActiveName)
      if (oldActiveName === '0' && this.addForm.goods_cat.length !== 3) {
        this.$message.error('请选择商品分类')
        return false
      }
    },
    // 点击tab栏时触发的事件，通过判断activeIndex值，来确定点击的tab栏
    async tabChange() {
      if (this.activeIndex === '1') {
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: 'many' }
          }
        )
        console.log(res)
        if (res.meta.status !== 200) {
          return this.$message.error('动态参数获取失败！')
        }
        // 循环数据，将attr_vals转为数组
        res.data.forEach(item => {
          item.attr_vals =
            item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ')
        })
        this.manyTableData = res.data
      } else if (this.activeIndex === '2') {
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: 'only' }
          }
        )
        console.log(res)
        this.onlyTableData = res.data
      }
    },
    // 预览图片
    handlePreview(file) {
      console.log(file)
      this.pathURL = file.response.data.url
      this.preDialogVisible = true
    },
    // 监听删除图片事件
    handleRemove(file) {
      // console.log(file)
      // 根据临时路径查找对应的图片
      const filePath = file.response.data.tmp_path
      const index = this.addForm.pics.findIndex(item => item.pic === filePath)
      // 从数组中删除
      this.addForm.pics.splice(index, 1)
      console.log(this.addForm.pics)
    },
    // 监听图片上传成功的事件
    addPic(response) {
      console.log(response)
      if (response.meta.status !== 200) {
        return this.$message.error('上传图片失败！')
      }
      this.$message.success('上传图片成功！')
      // 拼接图片对象
      const picInfo = { pic: response.data.tmp_path }
      // 添加到数组中
      this.addForm.pics.push(picInfo)
      console.log(this.addForm.pics)
    },
    // 添加商品
    addGoods() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return this.$message.error('请填写必要的信息')
        // 通过lodash深拷贝，防止类型冲突，表单中addform中的goods_cat为数组，但上传时要字符串，在转换后会报错，因为是使用同一个addform对象，所以报错
        const form = _.cloneDeep(this.addForm)
        console.log(form)
        // 将goods_cat转为字符串类型
        form.goods_cat = form.goods_cat.join()
        // 循环动态参数保存到attr数组中
        this.manyTableData.forEach(item => {
          // 对象拼接
          const attrInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(' ')
          }
          this.form.attr.push(attrInfo)
        })
        // 循环静态属性保存到attr数组中
        this.onlyTableData.forEach(item => {
          const attrInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          }
          this.form.attr.push(attrInfo)
        })
        // 上传商品
        const { data: res } = await this.$http.post('goods', form)

        if (res.meta.status !== 201) {
          return this.$message.error('添加商品失败！')
        }
        // 编程式导航，跳转到/goods
        this.$message.success('添加商品成功！')
        this.$router.push('/goods')
      })
    }
  },
  computed: {
    cateId() {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2]
      }
      return null
    }
  }
}
</script>

<style lang="less" scoped>
.el-steps {
  margin: 20px 0;
}
.el-checkbox {
  margin-right: 5px;
}
.addBtn {
  margin-top: 10px;
}
</style>
